package com.lgl.mes.barcode.service.impl;

import com.lgl.mes.barcode.entity.SpBarcode;
import com.lgl.mes.barcode.mapper.SpBarcodeMapper;
import com.lgl.mes.barcode.request.spBarcodeBatchAddReq;
import com.lgl.mes.barcode.service.ISpBarcodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lgl.mes.common.util.BarcodeUtil;
import com.lgl.mes.common.util.ServerAddressExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 75039960@qq.com
 * @since 2023-12-13
 */
@Service
public class SpBarcodeServiceImpl extends ServiceImpl<SpBarcodeMapper, SpBarcode> implements ISpBarcodeService {

    @Value("${server.port}")
    private   int serverPort;

    @Autowired
    private SpBarcodeMapper spBarcodeMapper;

    //@Async

    public boolean addBatch  (/*HttpServletRequest request,*/spBarcodeBatchAddReq req) throws UnknownHostException {

        if(req ==null) return false;


        if(req.getWidth()!=999) return false;
        //System.out.println("req= "+req);
        //System.out.println("count= "+req.getCount());

       String hostname = InetAddress.getLocalHost().getHostAddress();

       //String  hostaddress = ServerAddressExample.getServerAddress(request);

       System.out.println("hostname= "+hostname);
       //System.out.println("hostaddress= "+hostaddress);
       System.out.println("serverPort= "+serverPort);

        for (int  i  =0; i< req.getCount() ; i++)
        {

            SpBarcode  bc =  new  SpBarcode();
            bc.setBaseUrl(req.getBaseUrl());
            bc.setParam(req.getParam());
            bc.setCode( BarcodeUtil.generateRandomString(14));
            String url = req.getBaseUrl()+bc.getCode();
            if (! req.getParam().isEmpty() ) {
                url = url + "&" + req.getParam();
            }
            String imgPath = "images/"+bc.getCode()+".png";
            bc.setImgName(bc.getCode()+".png");
            bc.setFullImgUrl(hostname+":"+serverPort+"/"+imgPath);

            bc.setMemo(url);

            //System.out.println("url= "+ url);

            //System.out.println("memo= "+ bc.getMemo());


            BarcodeUtil.generateBarCode(url,BarcodeUtil.QR_CODE,imgPath);

            this.saveOrUpdate(bc);

        }
        return true;
    }


    public  int updateById_lgl ( SpBarcode  bc  ){
        return  this.baseMapper.updateById_lgl(bc);

       //return  spBarcodeMapper.updateById(bc);
        //sysRoleService.rebuild(record);
    }

}
